<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Resources\Result;
use App\Models\User;
use App\Models\Ranking;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Result::OK('查询成功', User::all());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // with() 方法预加载关联数据
        $user = User::with('score')
        ->find($id);
        $score = $user->score;

        // 添加上排名字段 score有withDefault不用判空，但是会执行一条多余的语句
        // 使用exists就会判断数据库是否有记录
        if($score->exists) {
            $score->user_rank = Ranking::getUserRank($id);
        }
        return Result::OK('查询成功', $user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'string|max:32',
            'phone' => 'integer|unique:user',
            'password' => 'string|between:6,32|confirmed',
            'gender' => 'string|size:1',
            'avatar' => 'url'
        ]);

        // 排除多余字段
        $userData = $request->only(['name', 'phone', 'password', 'gender', 'avatar']);
        User::where('id', $id)->update($userData);
        return Result::OK('更改成功');
    }
}
